package top.withwings.bonus.bonus.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.thymeleaf.util.DateUtils;
import top.withwings.bonus.bonus.pojo.OnSaleForm;
import top.withwings.bonus.bonus.service.OnSaleFormService;
import top.withwings.bonus.common.pojo.PageParam;
import top.withwings.bonus.common.pojo.PagedData;
import top.withwings.bonus.common.pojo.UnixTimestampToDateEditor;

import java.util.Date;

@CrossOrigin
@RestController
@RequestMapping("onSaleForm")
public class OnSaleController {
    @Autowired
    private OnSaleFormService onSaleFormService;


    @PostMapping("page")
    public PagedData<OnSaleForm> page(PageParam pageParam,Integer goodId,
                                      @RequestParam(required =false,defaultValue="false") boolean nowEffectiveOnly) {
        if(nowEffectiveOnly){
            Date today = DateUtils.createToday().getTime();
            return onSaleFormService.findByGoodAndTime(pageParam,goodId,today);
        }else {
            return onSaleFormService.findByGood(pageParam,goodId);
        }

    }

    @PostMapping("delete")
    public void delete(int id){
        onSaleFormService.delete(id);
    }

    @PostMapping("create")
    public void create(@RequestBody OnSaleForm onSaleForm){
        onSaleFormService.create(onSaleForm);
    }


    @PostMapping("update")
    public void update(@RequestBody OnSaleForm onSaleForm){
        onSaleFormService.update(onSaleForm);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //时间戳转date
        binder.registerCustomEditor(Date.class, new UnixTimestampToDateEditor());
    }

}
